package com.phb.puhuibao.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.glassfish.jersey.client.JerseyWebTarget;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easemob.server.comm.Constants;
import com.easemob.server.comm.HTTPMethod;
import com.easemob.server.comm.Roles;
import com.easemob.server.comm.HTTPClientUtils;
import com.easemob.server.jersey.utils.JerseyUtils;
import com.easemob.server.jersey.vo.ClientSecretCredential;
import com.easemob.server.jersey.vo.Credential;
import com.easemob.server.jersey.vo.EndPoints;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.idp.pub.service.IBaseService;
import com.idp.pub.web.controller.BaseController;
import com.phb.puhuibao.entity.GroupChat;
import com.phb.puhuibao.entity.MobileUser;
import com.fasterxml.jackson.databind.node.ArrayNode;

import org.apache.commons.lang3.StringUtils;

import java.net.URL;

@Controller
@RequestMapping(value = "/groupChat")
public class GroupChatController extends BaseController<GroupChat, String> {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupChatController.class);
	private static final String APPKEY = Constants.APPKEY;
	private static final JsonNodeFactory factory = new JsonNodeFactory(false);
    // 通过app的client_id和client_secret来获取app管理员token
    private static Credential credential = new ClientSecretCredential(Constants.APP_CLIENT_ID, Constants.APP_CLIENT_SECRET, Roles.USER_ROLE_APPADMIN);

    static final URL CHATGROUPS_URL = HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatgroups");
    
	@Resource(name = "groupChatService")
	public void setBaseService(IBaseService<GroupChat, String> baseService) {
		super.setBaseService(baseService);
	}
	@Resource(name = "mobileUserService")
	private IBaseService<MobileUser, String> mobileUserService;
	
	@Resource(name = "groupChatService")
	private IBaseService<GroupChat, String> groupChatService;
	
	@javax.annotation.Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	
/**
 * 创建群组
 * 
 */	
@RequestMapping(value="groupCreate")
@ResponseBody
public Map<String, Object> groupCreate(@RequestParam int muid,
		                               @RequestParam String groupname,
		                               @RequestParam String desc,
		                               @RequestParam int ispublic,
		                               @RequestParam String membersIds, 
		                               int maxusers 
		                              ) {
	Map<String, Object> data = new HashMap<String, Object>();
	
	
	try {
		
		/*
		 * {
		    "groupname":"testrestgrp12", //群组名称, 此属性为必须的
		    "desc":"server create group", //群组描述, 此属性为必须的
		    "public":true, //是否是公开群, 此属性为必须的
		    "maxusers":300, //群组成员最大数(包括群主), 值为数值类型,默认值200,此属性为可选的
		    "approval":true, //加入公开群是否需要批准, 默认值是true（加群需要群主批准）, 此属性为可选的
		    "owner":"jma1", //群组的管理员, 此属性为必须的
		    "members":["jma2","jma3"] //群组成员,此属性为可选的,但是如果加了此项,数组元素至少一个（注：群主jma1不需要写入到members里面）
		   }
		 * */
 
		 
		 
		ObjectNode dataObjectNode = JsonNodeFactory.instance.objectNode();
		dataObjectNode.put("groupname", groupname);
		dataObjectNode.put("desc", desc);
		dataObjectNode.put("public", (ispublic==1)?true:false);
		dataObjectNode.put("approval", false);
		dataObjectNode.put("maxusers", maxusers);
		dataObjectNode.put("owner", "puhuibao_"+muid);
		ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
		String[] members=membersIds.split(",");
		for(int i=0;i<members.length;i++){
			arrayNode.add("puhuibao_"+members[i]);
		}
		dataObjectNode.put("members", arrayNode);
		ObjectNode creatChatGroupNode = creatChatGroups(dataObjectNode);
		GroupChat entity = null;
        if (creatChatGroupNode != null && creatChatGroupNode.get("statusCode").asInt() == 200) {
            //LOGGER.info("创建组:" + creatChatGroupNode.toString());
            entity = new GroupChat();
            entity.setGroupId(creatChatGroupNode.get("data").get("groupid").asText());
            entity.setIsPublic(ispublic);
            entity.setMaxUsers(maxusers);
            entity.setGroupName(groupname);
            entity.setGroupDescscription(desc);
            entity.setGroupOwner("puhuibao_"+muid);
            entity.setGroupOwnerid(muid);
            entity.setMember(membersIds+","+muid);//群主也要加上啊
            groupChatService.save(entity);
        }
		
		/*
		 * {
			  "action" : "post",
			  "application" : "4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5",
			  "params" : { },
			  "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui",
			  "entities" : [ ],
			  "data" : {
			    "groupid" : "1411527886490154"
			  },
			  "timestamp" : 1411527886457,
			  "duration" : 125,
			  "organization" : "easemob-demo",
			  "applicationName" : "chatdemoui"
			}
		 * */
 
			data.put("result", entity);
		data.put("message", "");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", "网络异常！");
		data.put("status", 0);
		return data;
	}	
}

/**
 * 修改群组,暂时只能修改名字            本来可以修改人数和描述
 * 
 */	
@RequestMapping(value="groupUpdate")
@ResponseBody
public Map<String, Object> groupUpdate( @RequestParam String groupname,@RequestParam String groupid ) {
	Map<String, Object> data = new HashMap<String, Object>();
	
	
	try {

		ObjectNode dataObjectNode = JsonNodeFactory.instance.objectNode();
		dataObjectNode.put("groupname", groupname);
		ObjectNode updateChatGroupNode = updateChatGroups(dataObjectNode,groupid);
		GroupChat entity = null;
        if (updateChatGroupNode != null && updateChatGroupNode.get("statusCode").asInt() == 200) {
            entity = new GroupChat();
            entity.setGroupId(groupid);
            entity.setGroupName(groupname);
            groupChatService.update(entity);
            data.put("result", entity);
        }else if (updateChatGroupNode != null && updateChatGroupNode.get("statusCode").asInt() != 200) {
        	//data.put("message", deleteUserFromGroupNode.get("error_description").asText());
        	 throw new Exception(updateChatGroupNode.get("error_description").asText()) ; 
        }
        
		
 
		
		data.put("message", "修改成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}
	
/**
 * 获取群列表
 * 
 */		
@RequestMapping(value="getGroupsByUserId")
@ResponseBody
public Map<String, Object> getGroupsByIds(@RequestParam String  muid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("allmygroups", muid);
		List<GroupChat>  groupchatlist= groupChatService.findList(params);
        if (groupchatlist.size()>0) {
        	for(GroupChat groupchat:groupchatlist){
        		groupchat.setMember("");//去除用户信息,减少网络流量
        	}
    		 data.put("result", groupchatlist);
        }else  {
        	data.put("result", groupchatlist);
        }
		data.put("status", 1);
		return data;
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);
			return data;
		}	
}
	
/**
 * 删除群组
 * 
 */	 
@RequestMapping(value="deleteGroupById")
@ResponseBody
public Map<String, Object> deleteGroupById(@RequestParam String  groupid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		ObjectNode deleteChatGroupNode =  deleteChatGroups(groupid) ;
        if (deleteChatGroupNode != null && deleteChatGroupNode.get("statusCode").asInt() == 200) {
        	Map<String, Object> params=new HashMap<String, Object>();
    		params.put("groupId", groupid);
            groupChatService.delete(params);
        }
	 
		data.put("message", "删除成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", "网络异常！");
		data.put("status", 0);
		return data;
	}	
}
/**
 * 获取群员列表
 * 
 */
@RequestMapping(value="getMembersById")
@ResponseBody
public Map<String, Object> getMembersById(@RequestParam String  groupid,@RequestParam String  muid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("groupId", groupid);
		 GroupChat  groupchat= groupChatService.unique(params);
        if (groupchat != null) {
        	if(!StringUtils.isEmpty(groupchat.getMember()) ){//群里有成员
        		String[] temp = groupchat.getMember().split(",");
        		String ids="";
        		for(int i=0;i<temp.length;i++){
        			ids+=temp[i]+",";
        		}
        		ids=ids+groupchat.getGroupOwnerid();//把群主加进去
        		String sql = "SELECT   u.m_user_id , u.photo, u.sex, u.level, ifnull(f.follow_uname,u.nickname) nickname FROM phb_mobile_user u LEFT JOIN (SELECT follow_user, follow_uname FROM phb_muser_follow WHERE m_user_id="+muid+") f on(u.m_user_id = f.follow_user) WHERE u.m_user_id in("+ids+")";
        		List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql);
        		data.put("result", result);
        	}else{//群里没有成员
        		data.put("result", "");
        	}
        	
        }else{
        	data.put("result", "");
        }
		data.put("message", "");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", "网络异常！");
		data.put("status", 0);
		return data;
	}	
}
 
		
	
	
/**
 * 添加多个成员到群
 * 
 */	
@RequestMapping(value="addMembersByIds")
@ResponseBody
public Map<String, Object> addMembersByIds(@RequestParam String  groupid,@RequestParam String muids) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		ArrayNode usernames = JsonNodeFactory.instance.arrayNode();
		String[] ids = muids.split(",");
		for(int i=0;i<ids.length;i++){
			usernames.add("puhuibao_"+ids[i]);
		}
		ObjectNode usernamesNode = JsonNodeFactory.instance.objectNode();
		usernamesNode.put("usernames", usernames);
		String newmembers="";
		
		 
		
			String ownerid="";
		ObjectNode addUserToGroupBatchNode = addUsersToGroupBatch(groupid, usernamesNode);//成员添加到环信
        if (addUserToGroupBatchNode != null && addUserToGroupBatchNode.get("statusCode").asInt() == 200) {
			 ObjectNode getAllMemberssByGroupIdNode = getAllMemberssByGroupId(groupid);
	        	ArrayNode an = (ArrayNode) getAllMemberssByGroupIdNode.get("data");
	    			for(int i=0;i<an.size();i++){
	    				TextNode on = (TextNode) an.get(i).get("member");
	    				TextNode owner = (TextNode) an.get(i).get("owner");
	    				if(on!=null){
	    					String[] temp = on.asText().split("_");
	    					newmembers+=temp[1]+",";//取数字部分
	    				}
	    				if(owner!=null){
	    					String[] temp = owner.asText().split("_");
	    					ownerid=temp[1];//取数字部分
	    				}
	    			}
	    		 newmembers+=ownerid;//把群主的id拼上
	    	 
	    		 GroupChat  newgroupchat  = new GroupChat();
	    		 newgroupchat.setGroupId(groupid);
	    		 newgroupchat.setMember(newmembers);
	    		 groupChatService.update(newgroupchat);//把环信取到的当前群的成员更新到本地数据库
			 data.put("result", newmembers);
        }else if (addUserToGroupBatchNode != null && addUserToGroupBatchNode.get("statusCode").asInt() != 200) {
        	 throw new Exception(addUserToGroupBatchNode.get("error_description").asText()) ; 
        }
		
        data.put("message", "成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}

/**
 * 获取备选朋友列表,这个列表不包含已经在组里的成员
 * 
 */
@RequestMapping(value="getFriendListById")
@ResponseBody
public Map<String, Object> getFriendList(String  groupid,@RequestParam String muid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		String sql ="";
		if(StringUtils.isEmpty(groupid)){//创建群的时候,获取的列表
			sql = "SELECT  f.follow_user,u.photo,f.follow_uname ,u.sex,u.level FROM phb_muser_follow f LEFT JOIN phb_mobile_user u ON f.follow_user = u.m_user_id WHERE f.m_user_id = "+muid+" AND f.follow_user in (SELECT b.m_user_id  FROM phb_muser_follow b  WHERE b.follow_user = "+muid+"      AND (b.follow_isblocked IS NULL   OR b.follow_isblocked='0')) AND f.follow_user NOT IN (SELECT follow_user  FROM phb_muser_follow  WHERE m_user_id= "+muid+"  AND follow_isblocked ='1')";
		}else{//现有的群里加人,需要排除
			Map<String, Object> params=new HashMap<String, Object>();
			 params.put("groupId", groupid);
			 GroupChat  groupchat= groupChatService.unique(params);//获取当前组信息
			 String groupmembers=groupchat.getMember();
			 
			 if(StringUtils.isEmpty(groupmembers)){//现在有群,但是群里没有人,可能是删光了
				 sql = "SELECT  f.follow_user,u.photo,f.follow_uname ,u.sex,u.level FROM phb_muser_follow f LEFT JOIN phb_mobile_user u ON f.follow_user = u.m_user_id WHERE f.m_user_id = "+muid+" AND f.follow_user in (SELECT b.m_user_id  FROM phb_muser_follow b  WHERE b.follow_user = "+muid+"      AND (b.follow_isblocked IS NULL   OR b.follow_isblocked='0')) AND f.follow_user NOT IN (SELECT follow_user  FROM phb_muser_follow  WHERE m_user_id= "+muid+"  AND follow_isblocked ='1')";
			 }else{//现在有群,群里有人
				 sql = "SELECT  f.follow_user,u.photo,f.follow_uname ,u.sex,u.level FROM phb_muser_follow f LEFT JOIN phb_mobile_user u ON f.follow_user = u.m_user_id WHERE f.m_user_id = "+muid+" AND f.follow_user in (SELECT b.m_user_id  FROM phb_muser_follow b  WHERE b.follow_user = "+muid+"      AND (b.follow_isblocked IS NULL   OR b.follow_isblocked='0')) AND f.follow_user NOT IN (SELECT follow_user  FROM phb_muser_follow  WHERE m_user_id= "+muid+"  AND follow_isblocked ='1') AND f.follow_user NOT IN ("+groupmembers+")";
			 }
			
		}
		 
		 List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql);
		 data.put("result", result);
		 data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}
	
/**
 * 在群组中减少一个人
 */
@RequestMapping(value="deleteMemberById")
@ResponseBody
public Map<String, Object> deleteMemberById(@RequestParam String  groupid,@RequestParam String muid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		ObjectNode deleteUserFromGroupNode = deleteUserFromGroup(groupid, "puhuibao_"+muid);
		/*
		 *
		 *{
			  "action" : "delete",
			  "application" : "4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5",
			  "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui",
			  "entities" : [ ],
			  "data" : {
			    "action" : "remove_member",
			    "result" : true,
			    "groupid" : "1411816013089",
			    "user" : "q4xpsfjfvf"
			  },
			  "timestamp" : 1413012566573,
			  "duration" : 56,
			  "organization" : "easemob-demo",
			  "applicationName" : "chatdemoui"
			}
		 * 
		 * 
		 * */
		 String newmembers="";//群员ids
        if (deleteUserFromGroupNode != null && deleteUserFromGroupNode.get("statusCode").asInt() == 200) {
        	
        	ObjectNode getAllMemberssByGroupIdNode = getAllMemberssByGroupId(groupid);
        	/*
        	 * {
				  "action" : "get",
				  "uri" : "https://a1.easemob.com/easemob-demo/4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5/chatgroups/1411816013089/users",
				  "entities" : [ ],
				  "data" : [ {
				    "member" : "lidis"
				  }, {
				    "member" : "asdfgh"
				  }, {
				    "member" : "zhanglin"
				  }, {
				    "owner" : "ruson"
				  } ],
				  "timestamp" : 1413012431449,
				  "duration" : 24
				}
        	 * */
        	String ownerid="";
        	ArrayNode an = (ArrayNode) getAllMemberssByGroupIdNode.get("data");
    			for(int i=0;i<an.size();i++){
    				TextNode on = (TextNode) an.get(i).get("member");
    				TextNode owner = (TextNode) an.get(i).get("owner");
    				if(on!=null){
    					String[] temp = on.asText().split("_");
    					newmembers+=temp[1]+",";//取数字部分
    				}
    				if(owner!=null){
    					String[] temp = owner.asText().split("_");
    					ownerid=temp[1];//取数字部分
    				}
    			}
    			newmembers+=ownerid;//把群主的id拼上
    		 
    		 GroupChat  newgroupchat  = new GroupChat();
    		 newgroupchat.setGroupId(groupid);
    		 newgroupchat.setMember(newmembers);
    		 groupChatService.update(newgroupchat);//把环信取到的当前群的成员更新到本地数据库
    		
    		 data.put("result", newmembers);
        }else if (deleteUserFromGroupNode != null && deleteUserFromGroupNode.get("statusCode").asInt() != 200) {
        	//data.put("message", deleteUserFromGroupNode.get("error_description").asText());
        	 throw new Exception(deleteUserFromGroupNode.get("error_description").asText()) ; 
        }
        data.put("message", "成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}


/**
 * 获取群详情
 */
@RequestMapping(value="getGroupDetailById")
@ResponseBody
public Map<String, Object> getGroupDetailById(@RequestParam String  groupid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("groupId", groupid);
		GroupChat  groupchat= groupChatService.unique(params);//获取组信息
		data.put("result", groupchat);
        data.put("message", "成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}

/**
 * 获取群详情
 */
@RequestMapping(value="getGroupDetailByIdFromecmb")
@ResponseBody
public Map<String, Object> getGroupDetailByIdFromecmb(@RequestParam String  groupid) {
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		ObjectNode groupDetailNode = getGroupDetailsByChatgroupid(groupid);
		
		data.put("result", groupDetailNode);
        data.put("message", "成功");
		data.put("status", 1);
		return data;
	} catch (Exception e) {
		data.put("message", e.getLocalizedMessage());
		data.put("status", 0);
		return data;
	}	
}



 
//-------------------------------------------------------------------------------------------------------------------------------------------
		/**
		 * 删除群组
		 * 
		 */
		public static ObjectNode deleteChatGroups(String chatgroupid) {
			ObjectNode objectNode = factory.objectNode();
			// check appKey format
			if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
				LOGGER.error("Bad format of Appkey: " + APPKEY);
				objectNode.put("message", "Bad format of Appkey");
				return objectNode;
			}
			try {
				URL deleteChatGroupsUrl = HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatgroups/"
						+ chatgroupid);
				objectNode = HTTPClientUtils.sendHTTPRequest(deleteChatGroupsUrl, credential, null,
						HTTPMethod.METHOD_DELETE);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return objectNode;
		}
		
		
		
	
 
	
	/**
	 * 获取群组中的所有成员
	 * 
	 */
	public static ObjectNode getAllMemberssByGroupId(String chatgroupid) {

		ObjectNode objectNode = factory.objectNode();

		// check appKey format
		if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {

			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(chatgroupid).path("users");

			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_GET, null);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
	/**
	 * 在群组中添加一个人
	 * 
	 */
	public static ObjectNode addUserToGroup(String chatgroupid, String userName) {

		ObjectNode objectNode = factory.objectNode();

		// check appKey format
		if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {

			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(chatgroupid).path("users")
					.path(userName);

			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_POST, null);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}

	/**
	 * 在群组中减少一个人
	 * 
	 */
	public static ObjectNode deleteUserFromGroup(String chatgroupid, String userName) {
		ObjectNode objectNode = factory.objectNode();

		// check appKey format
		if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {
			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(chatgroupid).path("users")
					.path(userName);

			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_DELETE, null);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
	 
	
	/**
	 * 群组批量添加成员
	 * 
	 * @param toAddBacthChatgroupid
	 * @param usernames
	 * @return
	 */
	private static ObjectNode addUsersToGroupBatch(String toAddBacthChatgroupid, ObjectNode usernames) {
		ObjectNode objectNode = factory.objectNode();
		// check appKey format
		if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);
			objectNode.put("message", "Bad format of Appkey");
			return objectNode;
		}
		if (StringUtils.isBlank(toAddBacthChatgroupid.trim())) {
			LOGGER.error("Property that named toAddBacthChatgroupid must be provided .");
			objectNode.put("message", "Property that named toAddBacthChatgroupid must be provided .");
			return objectNode;
		}
		// check properties that must be provided
		if (null != usernames && !usernames.has("usernames")) {
			LOGGER.error("Property that named usernames must be provided .");
			objectNode.put("message", "Property that named usernames must be provided .");
			return objectNode;
		}

		try {
			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(toAddBacthChatgroupid).path("users");
					 
			objectNode = JerseyUtils.sendRequest(webTarget, usernames, credential, HTTPMethod.METHOD_POST, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
	/**
	 * 获取一个群组的详情
	 * 
	 * @return
	 */
	public static ObjectNode getGroupDetailsByChatgroupid(String chatgroupIDs) {
		ObjectNode objectNode = factory.objectNode();

		// check appKey format
		if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {

			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(chatgroupIDs);

			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_GET, null);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
	/**
	 * 创建群组
	 * 
	 */
	public static ObjectNode creatChatGroups(ObjectNode dataObjectNode) {
		ObjectNode objectNode = factory.objectNode();
		// check appKey format
		if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);
			objectNode.put("message", "Bad format of Appkey");
			return objectNode;
		}

		// check properties that must be provided
		if (!dataObjectNode.has("groupname")) {
			LOGGER.error("Property that named groupname must be provided .");
			objectNode.put("message", "Property that named groupname must be provided .");
			return objectNode;
		}
		if (!dataObjectNode.has("desc")) {
			LOGGER.error("Property that named desc must be provided .");
			objectNode.put("message", "Property that named desc must be provided .");
			return objectNode;
		}
		if (!dataObjectNode.has("public")) {
			LOGGER.error("Property that named public must be provided .");
			objectNode.put("message", "Property that named public must be provided .");
			return objectNode;
		}
		if (!dataObjectNode.has("approval")) {
			LOGGER.error("Property that named approval must be provided .");
			objectNode.put("message", "Property that named approval must be provided .");
			return objectNode;
		}
		if (!dataObjectNode.has("owner")) {
			LOGGER.error("Property that named owner must be provided .");
			objectNode.put("message", "Property that named owner must be provided .");
			return objectNode;
		}
		if (!dataObjectNode.has("members") || !dataObjectNode.path("members").isArray()) {
			LOGGER.error("Property that named members must be provided .");
			objectNode.put("message", "Property that named members must be provided .");
			return objectNode;
		}

		try {
			objectNode = HTTPClientUtils.sendHTTPRequest(CHATGROUPS_URL, credential, dataObjectNode,
					HTTPMethod.METHOD_POST);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
	/**
	 * 修改群组
	 * 
	 */
	public static ObjectNode updateChatGroups(ObjectNode dataObjectNode,String groupid) {
		ObjectNode objectNode = factory.objectNode();
		// check appKey format
		if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			LOGGER.error("Bad format of Appkey: " + APPKEY);
			objectNode.put("message", "Bad format of Appkey");
			return objectNode;
		}

		// check properties that must be provided
		if (!dataObjectNode.has("groupname")) {
			LOGGER.error("Property that named groupname must be provided .");
			objectNode.put("message", "Property that named groupname must be provided .");
			return objectNode;
		}
//		if (!dataObjectNode.has("description")) {//描述
//			LOGGER.error("Property that named groupname must be provided .");
//			objectNode.put("message", "Property that named groupname must be provided .");
//			return objectNode;
//		}
//		if (!dataObjectNode.has("maxusers")) {//人数
//		LOGGER.error("Property that named groupname must be provided .");
//		objectNode.put("message", "Property that named groupname must be provided .");
//		return objectNode;
//	}

		try {
			
			URL CHATGROUPS_UPDATEURL = HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatgroups/"+groupid);
			
//			JerseyWebTarget webTarget = EndPoints.CHATGROUPS_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
//					.resolveTemplate("app_name", APPKEY.split("#")[1]).path(groupid);
//
//			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_PUT, null);
			
			objectNode = HTTPClientUtils.sendHTTPRequest(CHATGROUPS_UPDATEURL, credential, dataObjectNode,HTTPMethod.METHOD_PUT);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
	
 
	 

	 
	
 
}
